package ch.bfh.medinfo.javafx.dice.b_1;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import ch.bfh.medinfo.javafx.dice.definition.StatisticalDice;
import ch.bfh.medinfo.javafx.dice.implementation.StatisticalFairDice;

public class DiceController {
	private StatisticalDice dice;

	// Backing-List
	private List<Integer> list;
	// List-Model
	private ObservableList<Integer> observableList;

	public DiceController() {
		// Create a new Dice
		this.dice = new StatisticalFairDice(1, 6);

		// Create the backing-List (Initialize it with the first values)
		list = new ArrayList<>();
		for (int i : dice.getStatistics()) {
			list.add(i);
		}
		// Create the list-Model (using the backing list)
		observableList = FXCollections.observableList(list);
	}

	@FXML
	private ResourceBundle resources;

	@FXML
	private URL location;

	@FXML
	private Label labelActualValueId;

	@FXML
	private ListView<Integer> statisticsView;

	@FXML
	void play(ActionEvent event) {
		playDice();
	}

	@FXML
	void initialize() {
		assert labelActualValueId != null : "fx:id=\"labelActualValueId\" was not injected: check your FXML file 'DiceLayout.fxml'.";
		assert statisticsView != null : "fx:id=\"statisticsView\" was not injected: check your FXML file 'DiceLayout.fxml'.";

		statisticsView.setItems(observableList);
	}

	public void playDice() {
		dice.play();
		int count = 0;
		for (int i : dice.getStatistics()) {
			if (observableList.get(count) != i)
				observableList.set(count, i);
			count++;
		}

		labelActualValueId.setText("" + dice.getActualValue());
	}
}
